package com.ikingtech.framework.sdk.data.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ikingtech.framework.sdk.context.security.Me;
import com.ikingtech.framework.sdk.utils.Tools;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.util.ClassUtils;

import java.time.LocalDateTime;

/**
 * @author tie yan
 */
@ConditionalOnClass({MetaObjectHandler.class})
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {

	@Override
	public void insertFill(MetaObject metaObject) {
		fillValIfNullByName("createBy", Me.id(), metaObject);
		fillValIfNullByName("createName", Me.name(), metaObject);
		fillValIfNullByName("createTime", LocalDateTime.now(), metaObject);
		fillValIfNullByName("updateBy", Me.id(), metaObject);
		fillValIfNullByName("updateName", Me.name(), metaObject);
		fillValIfNullByName("updateTime", LocalDateTime.now(), metaObject);
	}

	@Override
	public void updateFill(MetaObject metaObject) {
		fillValIfNullByName("updateBy", Me.id(), metaObject);
		fillValIfNullByName("updateName", Me.name(), metaObject);
		fillValIfNullByName("updateTime", LocalDateTime.now(), metaObject);
	}

	/**
	 * 填充值
	 *
	 * <br >先判断是否有手动设置
	 * <br >优先手动设置的值
	 * <br >field 类型相同时设置
	 *
	 * @param fieldName  属性名
	 * @param fieldVal   属性值
	 * @param metaObject MetaObject
	 */
	public static void fillValIfNullByName(String fieldName, Object fieldVal, MetaObject metaObject) {
		// 没有 set 方法
		if (!metaObject.hasSetter(fieldName)) {
			return;
		}

		// 如果用户有手动设置的值
		Object userSetValue = metaObject.getValue(fieldName);
		String setValueStr = Tools.Obj.string(userSetValue);
		if (Tools.Str.isNotBlank(setValueStr)) {
			return;
		}

		// field 类型相同时设置
		Class<?> getterType = metaObject.getGetterType(fieldName);
		if (ClassUtils.isAssignableValue(getterType, fieldVal)) {
			metaObject.setValue(fieldName, fieldVal);
		}
	}
}
